<?php

class Url {
    
    //编码表
    protected $table = array ( 0 => 'b', 1 => 'y', 2 => 'p', 3 => 'N', 4 => 'F', 5 => 'W', 6 => 'Q', 7 => 'k', 8 => 'D', 9 => 0, 10 => 'K', 11 => 1, 12 => 'X', 13 => 'w', 14 => 4, 15 => 'G', 16 => 'h', 17 => 'Z', 18 => 'g', 19 => 'v', 20 => 8, 21 => 'd', 22 => 'z', 23 => 'U', 24 => 2, 25 => 'f', 26 => 'r', 27 => 'E', 28 => 's', 29 => 'P', 30 => 'J', 31 => 9, 32 => 'B', 33 => 5, 34 => 7, 35 => 'T', 36 => 'V', 37 => 'O', 38 => 'm', 39 => 'C', 40 => 'n', 41 => 'M', 42 => 'A', 43 => 'e', 44 => 'i', 45 => 'l', 46 => 'o', 47 => 'u', 48 => 'H', 49 => 'a', 50 => 'L', 51 => 'c', 52 => 'S', 53 => 't', 54 => 'I', 55 => 'Y', 56 => 'j', 57 => 3, 58 => 'q', 59 => 'x', 60 => 'R', 61 => 6);
    
    //反转后的编码表
    protected $table_trans = array ( 'b' => 0, 'y' => 1, 'p' => 2, 'N' => 3, 'F' => 4, 'W' => 5, 'Q' => 6, 'k' => 7, 'D' => 8, 0 => 9, 'K' => 10, 1 => 11, 'X' => 12, 'w' => 13, 4 => 14, 'G' => 15, 'h' => 16, 'Z' => 17, 'g' => 18, 'v' => 19, 8 => 20, 'd' => 21, 'z' => 22, 'U' => 23, 2 => 24, 'f' => 25, 'r' => 26, 'E' => 27, 's' => 28, 'P' => 29, 'J' => 30, 9 => 31, 'B' => 32, 5 => 33, 7 => 34, 'T' => 35, 'V' => 36, 'O' => 37, 'm' => 38, 'C' => 39, 'n' => 40, 'M' => 41, 'A' => 42, 'e' => 43, 'i' => 44, 'l' => 45, 'o' => 46, 'u' => 47, 'H' => 48, 'a' => 49, 'L' => 50, 'c' => 51, 'S' => 52, 't' => 53, 'I' => 54, 'Y' => 55, 'j' => 56, 3 => 57, 'q' => 58, 'x' => 59, 'R' => 60, 6 => 61);

    /**
    * 用一个数字生成短网址
    * @param $num 数字 int
    * @return $res 返回一个简短的字符串 string
    */
    public function trans($num) {
        $res = '';
        while ($num > 62) {
            $res = $this->table[($num % 62)] . $res;
            $num = floor($num / 62);
        }

        if ($num > 0) {
            $res = $this->table[$num] . $res;
        }
        return $res;
    }
    
    
    /**
    * 把短网址转回数字
    * @param $str 短网址 string
    * @return $num 返回一个数字 int
    */
    public function back_trans($str) {
        $short_str = str_split($str);
        $short_num = array();
        foreach ($short_str as $value) {
            $short_num[] = $this->table_trans[$value];
        }
        $num = 0;
        $arr_count = count($short_num);
        for($i=0;$i<$arr_count-1;$i++){
            if($i>0){
               $num = ($num + $short_num[$i]) * 62;
            }else{
                $num = $short_num[$i] * 62;
            }
        }
        return $num + $short_num[$arr_count-1];
        
    }
    
 
}

